import { reqAddOrUpdateCart, reqDeleteCart, reqCartList, reqCartSwitchChecked } from "@/api"

export default {
    state: {
        shopArr: []
    },
    mutations: {
        SET_SHOP_ARR(state, arr) {
            // console.log(arr);
            state.shopArr = arr
        },
    },
    actions: {
        async getCartList({ commit }) {
            let res = await reqCartList()
            if (res.code == 200) {
                commit('SET_SHOP_ARR', res.data)
            }
        },
        async switchChecked({ commit }, { skuId, isChecked }) {
            // console.log(isChecked);
            let res = await reqCartSwitchChecked(skuId, isChecked);
            if (res.code == 200) {
                return 'ok'
            } else {
                return Promise.reject()
            }
        },
        checkAll({ commit, state, dispatch }, isChecked) {
            console.log(isChecked);
            let arr = []
            state.shopArr[0].cartInfoList.forEach(item => {
                let p = dispatch('switchChecked', { skuId: item.skuId, isChecked })
                arr.push(p)
            })

            return Promise.all(arr)
        },
        async addOrUpdateCart({ commit }, { skuId, skuNum }) {
            let res = await reqAddOrUpdateCart(skuId, skuNum)
            if (res.code == 200) {
                return 'ok'
            } else {
                return Promise.reject(res.message)
            }
        },
        async deleteItem({ commit }, id) {
            let res = await reqDeleteCart(id)
            if (res.code == 200) {
                return 'ok'
            } else {
                return Promise.reject()
            }
        },
        async deleteAll({ commit, dispatch, state }) {
            let arr = []
            state.shopArr[0].cartInfoList.forEach(item => {
                if (item.isChecked == 1) {
                    let p = dispatch('deleteItem', item.skuId)
                    arr.push(p)
                }

            })
            return Promise.all(arr)
        },
    },
    getters: {
        cartInfo(state) {
            return state.shopArr[0] || {}
        }
    }
}